function [mac_capacity, fig_handle] = uplink_capacity(SNR_dB, num_users)
% 上行链路MAC容量分析
% 输入:
%   SNR_dB - 信噪比范围 (dB)
%   num_users - 用户数量数组
% 输出:
%   mac_capacity - MAC容量矩阵
%   fig_handle - 图形句柄

    SNR_linear = 10.^(SNR_dB/10);
    mac_capacity = zeros(length(SNR_dB), length(num_users));
    
    % 添加路径
    addpath('../Common');
    colors = color_definitions();
    
    fprintf('=== 上行链路MAC容量分析 ===\n');
    
    for user_idx = 1:length(num_users)
        K = num_users(user_idx);
        fprintf('仿真 %d 用户MAC容量...\n', K);
        
        for snr_idx = 1:length(SNR_dB)
            snr = SNR_linear(snr_idx);
            
            % 生成用户信道增益
            user_gains = sqrt(0.5) * (randn(1, K) + 1i * randn(1, K));
            user_powers = abs(user_gains).^2;
            
            % MAC容量计算: C_sum = log2(1 + sum(SNR_k))
            total_snr = snr * sum(user_powers);
            mac_capacity(snr_idx, user_idx) = log2(1 + total_snr);
        end
    end
    
    % 绘制结果
    fig_handle = figure('Name', '上行链路MAC容量', 'Position', [100, 100, 800, 600]);
    
    subplot(2,2,1);
    for user_idx = 1:length(num_users)
        plot(SNR_dB, mac_capacity(:, user_idx), ...
             ['-', colors(user_idx)], 'LineWidth', 2);
        hold on;
    end
    grid on;
    xlabel('SNR (dB)');
    ylabel('和速率 (bps/Hz)');
    title('MAC信道容量');
    legend(arrayfun(@(x) sprintf('%d用户', x), num_users, 'UniformOutput', false));
    
    % 容量与用户数量的关系
    snr_fixed = 15; % dB
    snr_idx = find(SNR_dB == snr_fixed, 1);
    subplot(2,2,2);
    plot(num_users, mac_capacity(snr_idx, :), 'o-', 'LineWidth', 2);
    grid on;
    xlabel('用户数量');
    ylabel('和速率 (bps/Hz)');
    title(sprintf('MAC容量 vs 用户数量 (SNR=%d dB)', snr_fixed));
    
    % 多用户分集增益
    subplot(2,2,3);
    for user_idx = 2:length(num_users)
        diversity_gain = mac_capacity(:, user_idx) - mac_capacity(:, 1);
        plot(SNR_dB, diversity_gain, ['-', colors(user_idx)], 'LineWidth', 2);
        hold on;
    end
    grid on;
    xlabel('SNR (dB)');
    ylabel('多用户分集增益 (bps/Hz)');
    title('多用户分集增益');
    legend(arrayfun(@(x) sprintf('%d用户', x), num_users(2:end), 'UniformOutput', false));
    
    % 频谱效率
    subplot(2,2,4);
    spectral_efficiency = mac_capacity ./ (num_users' * ones(1, length(SNR_dB)))';
    for user_idx = 1:length(num_users)
        plot(SNR_dB, spectral_efficiency(:, user_idx), ...
             ['-', colors(user_idx)], 'LineWidth', 2);
        hold on;
    end
    grid on;
    xlabel('SNR (dB)');
    ylabel('频谱效率 (bps/Hz/用户)');
    title('每用户频谱效率');
end